<template>
  <div
    class="fixed bottom-[5%] left-[50%] translate-x-[-50%] w-[90%] h-[60px] bg-white rounded-[57px] shadow-2xl z-[999]"
  >
    <ul class="flex justify-between h-full px-[30px]">
      <li
        class="flex flex-col items-center justify-center"
        v-for="(item, index) in tabbarArray"
        :key="index"
        @click="tabbarHandle(index)"
      >
        <img
          :src="item.icon"
          class="w-[22px] h-[22px] mt-[5px]"
          :class="`yourdiv${index}`"
          alt=""
        />
        <span
          class="text-[12px] mt-[5px] text-[#b0b0b0]"
          :class="props.index == index ? 'active' : ''"
        >
          {{ item.name }}
        </span>
      </li>
    </ul>
  </div>
  <!--------------------------------------------------------------------->
  <!--  弹出层 上传图片 start-->
  <var-popup v-model:show="popupShow" position="bottom">
    <div class="w-full h-[40px] leading-[40px] pl-[20px] pt-[10px] text-[18px]">
      上传图片
    </div>
    <div class="popup-example-block">
      <var-loading description="上传中...." type="circle" :loading="loading">
        <var-uploader
          v-model="files"
          :maxlength="1"
          @after-read="handleAfterRead"
        />
        <var-button
          class="mt-[35px]"
          type="success"
          color="#3a7afe"
          block
          @click="newUploadImgs"
        >
          上传图片
        </var-button>
      </var-loading>
    </div>
  </var-popup>
  <!--  弹出层 上传图片 end-->
</template>

<script setup lang="ts">
import { debounce } from "@/utils/utils";
import { ref, onMounted } from "vue";
import { uploadImg, adduploadImg } from "@/api/usersApi";
import { fileUpLoad, mergeFile, verifyFile } from "@/api/uploadApi";
import { useRouter } from "vue-router";
import { Snackbar } from "@varlet/ui";
import useUploads from "@/hooks/uploadsHooks/useUploads";
const { createChunks, calculateHash } = useUploads();
const router = useRouter();
const props = defineProps({
  index: {
    type: Number,
    default: 0,
  },
});
let partList = null;
const tabbarIndex = ref<number>(0);
const tabbarArray = ref([
  {
    name: "喜欢",
    icon: new URL("../../assets/img/tabbar/photo.png", import.meta.url).href,
  },
  {
    name: "发现",
    icon: new URL("../../assets/img/tabbar/find.png", import.meta.url).href,
  },
  {
    name: "",
    icon: new URL("../../assets/img/tabbar/add.png", import.meta.url).href,
  },
  {
    name: "影像馆",
    icon: new URL("../../assets/img/tabbar/photo.png", import.meta.url).href,
  },
  {
    name: "我",
    icon: new URL("../../assets/img/tabbar/me.png", import.meta.url).href,
  },
]);
const popupShow = ref<boolean>(false);
const files = ref<any>([]);
const uploadParams = ref(null);
const loading = ref<boolean>(false);
const filename = ref<string>("");
onMounted(() => {
  tabbarIndex.value = props.index;
  open(props.index);
});
/**
 * 切换 tabbar 选项卡
 */
const tabbarHandle = debounce((index) => {
  tabbarIndex.value = index;
  const tabbarRoute = ["Index", "Pageone", "", "Pagetwo", "User"];
  if (index == 2) {
    popupShow.value = true;
  } else {
    router.push({
      path: `/home${tabbarRoute[tabbarIndex.value]}`,
    });
  }
}, 100);
/**
 * 展示上传的图片
 * @param file
 */
const handleAfterRead = (file: any) => {
  const imgObj = {
    cover: file.cover,
    url: file.url,
    name: file.name,
  };
  files.value[0] = imgObj;
  uploadParams.value = file.file;
};

// 发送上传请求
async function handleUpLoad(partList) {
  let data = await verifyFile(filename.value); // 获取当前上传进度
  if (!data.needUpLoad) {
    files.value = [];
    Snackbar.success(data.message);
    return;
  }
  // 过滤掉已经上传完成的
  partList = partList.filter((part) => {
    let currentFile = data.uploadList.find(
      (item) => item.filename === part.chunkname
    );
    // 如果当前的part不存在
    if (!currentFile) {
      part.loaded = 0;
      return true;
    }
    // 用于刷新以后 或者断点续传时保存当前已经上传的大小
    // state.currentUploadSize += currentFile.size!;
    // if (currentFile.size < part.size) {
    //   part.loaded = currentFile.size;
    //   return true;
    // }
    return false;
  });
  console.log(partList, "---------------------");
  // 用来取消请求
  return Promise.all(
    partList.map((item, index) => {
      return fileUpLoad(
        item.chunk.slice(item.loaded),
        item.filename!,
        item.chunkname!,
        item.loaded!
      );
    })
  );
}

/**
 * 上传文件
 */
const uploadImgs = async () => {
  return;
  if (!uploadParams.value) {
    return Snackbar.warning("请先上传图片！");
  }
  loading.value = true;
  let formData = new FormData();
  formData.append("file", uploadParams.value);
  try {
    const { code, data } = await uploadImg(formData);
    if (code == 200) {
      const params = {
        url: data,
        photo_name: files.value[0].name,
        phone: localStorage.getItem("phone"),
      };
      const res = await adduploadImg(params);
      if (res.code == 200) {
        loading.value = false;
        files.value = [];
        Snackbar.success(res.message);
      }
    }
  } catch (e) {
    Snackbar.error(e);
  }
};
const newUploadImgs = async () => {
  // @ts-ignore
  if (!uploadParams.value) {
    return Snackbar.warning("请先上传图片！");
  }
  loading.value = true;
  files.value[0].state = "loading";
  // 分片
  partList = createChunks(uploadParams.value!);
  // 计算哈希（为秒传提供支持）通过webworker计算
  let fileHash = await calculateHash(partList);
  let { name } = uploadParams.value!;
  let DotIndex = name.lastIndexOf(".");
  let extName = name.slice(DotIndex);
  // 最后的文件名
  filename.value = `${fileHash}${extName}`;
  // 添加每个分块的名称
  partList.forEach((item, index) => {
    item.filename = filename.value;
    item.chunkname = `${filename.value}-${index}`;
  });
  try {
    let data = await handleUpLoad(partList);
    if (data) {
      const { code, message } = await mergeFile(
        filename.value,
        localStorage.getItem("phone")
      );
      if (code == 200) {
        loading.value = false;
        files.value = [];
        // files.value[0].state = "success";
        Snackbar.success(message);
      }
    }
    loading.value = false;
  } catch (error) {
    console.error(error);
    loading.value = false;
  }
};
const open = (index: string | number) => {
  const selector = document.querySelector(`.yourdiv${index}`);
  if (selector.className.includes("swashIn")) {
    return selector.classList.remove("magictime", "swashIn");
  }
  selector.classList.add("magictime", "swashIn");
};
</script>

<style lang="less" scoped>
.popup-example-block {
  padding: 20px 24px;
}
.active {
  //color: #fdc5d2;
  color: #000000;
}
.magictime.swashIn {
  -webkit-animation-duration: 0.5s;
  animation-duration: 0.5s;
}
</style>
